package com.edais.service.imp.gift;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.edais.domain.ErrorMessageSetting;
import com.edais.domain.User;
import com.edais.domain.gift.GiftPackageOrder;
import com.edais.service.ErrorMessageService;
import com.edais.service.GiftPackageExchangeFunction;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DateUtil;

/**
 * K码礼包兑换
 * Created by haoyx on 2016/11/17.
 */
/**
 * @author admin
 *
 */
@Service("kcodeExchangeImpl")
public class KcodeExchangeImpl implements GiftPackageExchangeFunction {

	private static final Logger logger = Logger.getLogger(WelfareExchangeImpl.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private ErrorMessageService errorMessageService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String, String> apply(Map<String, Object> params) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String error = validParams(params);
		if (!StringUtils.isEmpty(error)) {
			logger.info(error);
			error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, error);
			resMap.put("error", error);
			return resMap;
		}
		Long userId = Long.parseLong(params.get("userId").toString());
		String mobile = String.valueOf(params.get("mobile"));
		GiftPackageOrder packageOrder = (GiftPackageOrder) params.get("packageOrder");
		String logInfo = "兑换K码礼包" + packageOrder.getId() + userId + "-";
		logger.info(logInfo + "开始");
		User user = this.userService.selectUser(userId, mobile);
		if (null == user) {
			logger.info(logInfo + "查询不到此用户");
			error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, "查询不到此用户");
			resMap.put("error", error);
			return resMap;
		}
		
		String checkMsg=checkStatus(packageOrder.getStatus());
		if(checkMsg!=null){
			resMap.put("error", checkMsg);
			return resMap;
		}
		
//		if (!GiftPackageOrder.STATUS_INIT.equals(packageOrder.getStatus())) {
//			error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
//					Consts.ErrorMsg.MSG00001, "状态异常");
//			resMap.put("error", error);
//			return resMap;
//		}
		Date startDate = packageOrder.getStartDate();
		if (userService.getSysdate().before(startDate)) {
			int day= DateUtil.daysBetween( userService.getSysdate(),startDate); 
			error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, "还剩"+day +"天可以兑换");
			resMap.put("error", error);
			return resMap;
		}
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> exchangeMap = new HashMap<String, Object>();
		exchangeMap.put("userId", userId);
		exchangeMap.put("packageOrderId", packageOrder.getId());
		Map coreMap = CommonUtil.invokeCore(logInfo, "kcodeGiftPackageExchangeService", exchangeMap);
		if (coreMap == null || !"00000".equals(coreMap.get("rescode"))) {
			logger.error(logInfo + "兑换K码礼包异常" + coreMap.get("resmsg"));
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "兑换K码礼包异常");
			return coreMap;
		}
		logger.info(logInfo + "兑换K码礼包结束");
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		logger.info(logInfo + "结束");
		return coreMap;
	}

	private String checkStatus(String status) throws IllegalArgumentException, IllegalAccessException {

		if(status.equals(GiftPackageOrder.STATUS_SUCCESS)){
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000031");
			return CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",getErrorMsg(errorMap));
		}
		
		if(status.equals(GiftPackageOrder.STATUS_FAILED)){
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000032");
			return CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",getErrorMsg(errorMap));
		}
		
		if(status.equals(GiftPackageOrder.STATUS_FROZEN)){
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000033");
			return CommonUtil.setResultStringCn(errorMap, Consts.CHECK_CODE, "",getErrorMsg(errorMap));
		}
		
		return null;
	}

	private String getErrorMsg(Map<String, Object> errorMap) {
		// TODO Auto-generated method stub
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}

	
	@Override
	public String validParams(Map params) {
		if (null == params || params.isEmpty())
			return "参数列表不能为空";
		if (!params.containsKey("packageOrder") || null == params.get("packageOrder"))
			return "参数packageOrder不能为空";
		if (!params.containsKey("userId") || StringUtils.isEmpty(params.get("userId")))
			return "参数userId不能为空";
		if (!params.containsKey("mobile") || StringUtils.isEmpty(params.get("mobile")))
			return "参数mobile不能为空";
		return null;
	}
}
